package com.tangyuan.video.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangyuan.common.config.RedissonConfig;
import com.tangyuan.common.result.Result;
import com.tangyuan.common.result.ResultCodeEnum;
import com.tangyuan.dto.UserActionDto;
import com.tangyuan.feignapis.user.IUserActionFeignClient;
import com.tangyuan.model.UserAction;
import com.tangyuan.model.Video;
import com.tangyuan.model.VideoThump;
import com.tangyuan.video.mapper.VideoMapper;
import com.tangyuan.video.mapper.VideoThumpMapper;
import com.tangyuan.video.service.IVideoHotService;
import com.tangyuan.video.service.VideoThumpService;
import lombok.NoArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: video_thump
 * @Author: jeecg-boot
 * @Date: 2024-03-12
 * @Version: V1.0
 */
@Service
@NoArgsConstructor
public class VideoThumpServiceImpl extends ServiceImpl<VideoThumpMapper, VideoThump> implements VideoThumpService {

    @Autowired
    VideoMapper videoMapper;
    @Autowired
    IVideoHotService videoHotService;

    @Autowired
    private IUserActionFeignClient userActionFeignClient;

    private final RedissonClient redissonClient = RedissonConfig.createRedissonClient();

    @Override
    public Result<Object> addVideoThump(Long videoId, Long userId) {
        Video video = videoMapper.selectById(videoId);
        if(video == null){
            return Result.fail(ResultCodeEnum.NO_SEARCH_DATA.getMessage());
        }
        RLock lock = redissonClient.getLock("videoThump" + videoId + "-" + userId);
        lock.lock();
        try {

            UserActionDto dto = new UserActionDto();
            dto.setUserId(userId);
            dto.setMovieId(videoId);
            dto.setCategoryId(video.getCategoryId());

            LambdaQueryWrapper<VideoThump> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(VideoThump::getUserId, userId);
            queryWrapper.eq(VideoThump::getVideoId, videoId);
            VideoThump thump = this.getOne(queryWrapper);

            LambdaQueryWrapper<UserAction> actionWrapper = new LambdaQueryWrapper<>();
            actionWrapper.eq(UserAction::getUserId, userId);
            actionWrapper.eq(UserAction::getMovieId, videoId);
            if (thump == null) {
                thump = new VideoThump();
                thump.setVideoId(videoId);
                thump.setUserId(userId);
                thump.setCreateTime(new Date());
                likeVideoThump(thump);
                dto.setThump(1.0f);
                userActionFeignClient.getUserAction(dto);
            } else {
                if (thump.getIsDelete() == 0) {
                    cancelVideoThump(thump);
                    dto.setThump(-1.0f);
                    userActionFeignClient.getUserAction(dto);
                } else {
                    likeVideoThump(thump);
                    dto.setThump(1.0f);
                    userActionFeignClient.getUserAction(dto);
                }
            }
        } catch (Exception e) {
            log.error("点赞异常:" + e.toString());
        } finally {
            lock.unlock();
        }
        return Result.ok();
    }

    /**
     * 分页获取我点赞的视频ID
     * @param userId 用户ID
     * @return VideoId
     */

    @Override
    public List<Long> getVideoIdByUserId(Long userId, Integer pageNum, Integer pageSize) {
        if(userId == null || userId == 0){
            return new ArrayList<>();
        }
        QueryWrapper<VideoThump> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(VideoThump::getUserId,userId);
        wrapper.lambda().eq(VideoThump::getIsDelete,0);
        wrapper.lambda().orderByDesc(VideoThump::getCreateTime);
        List<VideoThump> records = baseMapper.selectPage(new Page<>(pageNum, pageSize), wrapper).getRecords();
        if(CollectionUtils.isEmpty(records)){
            return new ArrayList<>();
        }
        return records.stream().map(VideoThump::getVideoId).collect(Collectors.toList());
    }


    // 点赞视频
    private void likeVideoThump(VideoThump thump) {
        if (thump.getId() == null) {
            baseMapper.insert(thump);
        } else {
            baseMapper.update(null, new LambdaUpdateWrapper<VideoThump>()
                    .set(VideoThump::getIsDelete, 0)
                    .set(VideoThump::getUpdateTime, new Date())
                    .eq(VideoThump::getId, thump.getId()));
        }
        // 视频表点赞数量加一
        videoMapper.saveThumpUpNum(thump.getVideoId(), 1);
        videoHotService.determineHot(thump.getVideoId());

    }

    // 取消点赞
    private void cancelVideoThump(VideoThump thump) {
        baseMapper.update(null, new LambdaUpdateWrapper<VideoThump>()
                .set(VideoThump::getIsDelete, 1)
                .eq(VideoThump::getId, thump.getId()));
        // 视频表点赞数量减一
        videoMapper.saveThumpUpNum(thump.getVideoId(), -1);
    }
}
